package com.hup.minicontroller.client.service;

import android.content.Context;
import android.util.Log;

import com.hup.minicontroller.client.ClientApplication;
import com.hup.minicontroller.client.model.AppConfig;
import com.hup.minicontroller.client.model.AppState;
import com.hup.minicontroller.client.mvp.IClientHandler;
import com.hup.minicontroller.client.mvp.IClientHandler.ClientHandlerList;
import com.hup.minicontroller.common.framework.NotCrashExceptionHandler;
import com.hup.minicontroller.common.framework.SubThreadHandler;

import lombok.Getter;


public class MainService {
    private static final String TAG = MainService.class.getSimpleName();
    /**
     * 开发模式,打包时修改
     */
    public static final boolean DEV_MODE = true;
    @Getter
    private final AppState appState;

    public MainService(Context context) {
        if (DEV_MODE) NotCrashExceptionHandler.registerHandler();
        appState = new AppState();
        appState.getAppConfig().loadConfig(context.getSharedPreferences(AppConfig.class.getSimpleName(), Context.MODE_PRIVATE));

        initBean();
    }

    private void initBean() {
        //lan,蓝牙,lan广播
        ClientApplication.putBean(this);
        SubThreadHandler.registerSubThreadHandler("SubThreadHandler");
        ClientHandlerList clientHandlers = new ClientHandlerList();
        DataHandlerService dataHandlerService = new DataHandlerService();
        clientHandlers.add(new LanClientService(dataHandlerService));
        clientHandlers.add(new BluetoothClientService(dataHandlerService));
        ClientApplication.putBean(ClientHandlerList.class, clientHandlers);
        ClientApplication.putBean(new LanBroadcastReceiverService());
        ClientApplication.putBean(new BluetoothDeviceService());
    }

    public void doTerminate() {
        Log.i(TAG, "doTerminate: ");
        SubThreadHandler subThreadHandler = ClientApplication.getBean(SubThreadHandler.class);
        subThreadHandler.post(() -> ClientApplication.executeForeach(ClientHandlerList.class, IClientHandler::doTerminate));
        ClientApplication.executeIfExist(LanBroadcastReceiverService.class, LanBroadcastReceiverService::doTerminate);
        ClientApplication.executeIfExist(BluetoothDeviceService.class, BluetoothDeviceService::doTerminate);
        subThreadHandler.postDelayed(() -> {
            Log.i(TAG, "doTerminate: 马上会执行exit");
            System.exit(0);
        }, 500);
    }

}
